package com.ayitubie.refuelweb.config.crypto;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.dubbo.common.URL;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

@Component
public class CryptoUtil {
    /***
     * key和iv值可以随机生成,确保与前端的key,iv对应
     */
    private static String KEY = "abcdefgh12345678";
    private static String IV = "12345678abcdefgh";

    public static void main(String[] args) {
        String enString = URL.encode(encrypt("{\"ticketUid\":\"123456\"}"));
        System.out.println("enString = " + enString);
        System.out.println("deString = " + desEncrypt("xc5g0ngnPpCnVl1lBykJE76jyV1%2BCdAC245tlHGdv9Jzvcn5Pz6AUUrgSQnvGVDg"));
    }
    /***
     * 加密
     *
     * @param data 要加密的数据
     * @return encrypt
     */
    public static String encrypt(String data) {
        return encrypt(data, KEY, IV);
    }
    /***
     *  解密
     * @param data 要解密的数据
     */
    public static String desEncrypt(String data) {
        return desEncrypt(data, KEY, IV);
    }
    /**
     * 加密方法
     */
    private static String encrypt(String data, String key, String iv) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new Base64().encodeToString(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 解密方法
     */
    private static String desEncrypt(String data, String key, String iv) {
        try {
            byte[] encrypted1 = new Base64().decode(URL.decode(data));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keySpec,ivSpec);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original).trim();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
